/*
 * Copyright (c) 2018-2022 Caratacus, (caratacus@qq.com).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.crown.service.impl;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.crown.config.properties.WereWolfPropertie;
import org.crown.model.entity.File;
import org.crown.mapper.FileMapper;
import org.crown.service.IFileService;
import org.crown.framework.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Caratacus
 */
@Service
public class FileServiceImpl extends BaseServiceImpl<FileMapper, File> implements IFileService {

    public static String separator = "/";

    @Autowired
    private WereWolfPropertie wereWolfPropertie;


    public String getLocationDir(){

        String uploadPath = wereWolfPropertie.getFileUploadPath();

        if(!StringUtils.isEmpty(uploadPath)){

            return uploadPath+separator+ DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        }

        String locationDir = System.getProperty("user.home") + separator + "were-wolf/uploadDir";

        return locationDir+separator+ DateFormatUtils.format(new Date(),"yyyy-MM-dd");
    }

    @Override
    @Transactional(readOnly = false)
    public int putFile(MultipartFile file, String fileName) {

        int fileId = 0;
        try {
            InputStream local = file.getInputStream();
            Integer fileSize = local.available();

            if(StringUtils.isEmpty(fileName)) fileName = file.getOriginalFilename();

            String remoteFilePath = getLocationDir()+separator;

            remoteFilePath+=fileName;

            uploadFile(remoteFilePath,file.getInputStream());

            File sysFile = new File();
            sysFile.setFileName(fileName);
            sysFile.setFileAddress(remoteFilePath);
            sysFile.setFileSize(Long.parseLong(fileSize+""));
            sysFile.setFileType(FilenameUtils.getPrefix(fileName));

            this.save(sysFile);

            fileId = sysFile.getId();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileId;
    }

    private boolean uploadFile(String remoteFilePath, InputStream local){
        while(remoteFilePath.startsWith(separator)) {
            remoteFilePath = StringUtils.substring(remoteFilePath, 1);
        }

        String fileDir = FilenameUtils.getFullPathNoEndSeparator(remoteFilePath);


        boolean changeDirOk = false;
        if(StringUtils.isNotBlank(fileDir)) {
            java.io.File dirFile = new  java.io.File(fileDir);
            changeDirOk = dirFile.isDirectory();
            if(!changeDirOk) {
                makeDirs(fileDir);
            }
        }
        boolean uploadOk = true;


        try {

            FileUtils.copyInputStreamToFile(local,new java.io.File(remoteFilePath));
        } catch (IOException e) {
            e.printStackTrace();

            uploadOk =false;
        }

        return uploadOk;
    }

    private  void makeDirs(String fileDir){
        java.io.File dir = new java.io.File(fileDir);

        try {
            FileUtils.forceMkdir(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
